package com.jbwz.web.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jbwz.web.common.base.BaseServiceImpl;
import com.jbwz.web.common.base.IBasePage;
import com.jbwz.web.common.session.SecurityUserHolder;
import com.jbwz.web.security.entity.Resource;
import com.jbwz.web.security.entity.RoleResource;
import com.jbwz.web.security.entity.vo.MenuTreeVO;
import com.jbwz.web.security.entity.vo.RoleResourceVO;
import com.jbwz.web.security.enums.AdminFlagEnum;
import com.jbwz.web.security.mapper.RoleResourceMapper;
import com.jbwz.web.security.service.ResourceService;
import com.jbwz.web.security.service.RoleResourceService;
import com.jbwz.web.security.util.MenuTreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色资源关联 服务实现类
 *
 * @author yyh
 * @since 2021-07-18 22:02:17
 */
@Service
public class RoleResourceServiceImpl extends BaseServiceImpl<RoleResourceMapper, RoleResource>
        implements RoleResourceService {
    @Autowired
    private ResourceService resourceService;

    @Override
    public IBasePage pageList(IBasePage page, RoleResourceVO vo) {
        //        return baseMapper.pageList(page, vo);
        return null;
    }

    @Override
    public Set<Long> listByRoleId(Long roleId) {
        QueryWrapper<RoleResource> qw = Wrappers.<RoleResource>query().eq("role_id", roleId);
        List<RoleResource> roleResources = baseMapper.selectList(qw);
        return roleResources.stream().map(RoleResource::getResourceId).collect(Collectors.toSet());
    }

    @Override
    public void removeByRoleId(Long roleId) {
        UpdateWrapper<RoleResource> uw = Wrappers.<RoleResource>update().ge("role_id", roleId);
        baseMapper.delete(uw);
    }

    @Override
    public MenuTreeVO listByRVoByRoleIds(List<Long> currentRoleIds) {
        List<Resource> resourceList;
        if (AdminFlagEnum.SUPER_ADMIN.getCode().equals(SecurityUserHolder.getCurrentUser().getAdminFlag())) {
            resourceList = resourceService.list();
        } else {
            if (CollectionUtils.isEmpty(currentRoleIds)) {
                return new MenuTreeVO();
            }
            resourceList = baseMapper.listByResourceByRoleIds(currentRoleIds);
        }
        return MenuTreeUtil.toMenuTreeVO(resourceList);
    }
}
